const {
  updateWorkOrder
} = require('../../../api/workOrder')
const {
  queryFaultTypeOptions
} = require('../../../api/faultType')
const {
  queryMaintenanceModeOptions
} = require('../../../api/maintenanceMode')
const {
  clearEmptyKey
} = require('../../../utils/clearEmptyKey')
const {
  SERVICE_MODE,
  DIFFICUIT_FAULT,
  WORD_ORDER_OPERATION_TYPE
} = require('../../../constant/index')
const {
  to,
  openLoading,
  closeLoading,
  showToast,
  backParentLoad,
  getEventData,
  routeWithToken
} = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    DIFFICUIT_FAULT,
    formData: {
      operationContent: '',
      appointmentTime: '',
      difficultFault: DIFFICUIT_FAULT.not,
      addPartsOutParams: []
    },
    difficultFaultOptions: [{
      name: DIFFICUIT_FAULT.not,
      text: '否'
    }, {
      name: DIFFICUIT_FAULT.yes,
      text: '是'
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      orderData: JSON.parse(this.options.data)
    })
    this.getFaultTypeOptions()
  },

  onCustomTypeChange(event) {
    const {
      type
    } = getEventData(event)
    this.setData({
      [`formData.${type}`]: event.detail
    })

    this.clearForm(type)

    if (type === 'faultTypeId') {
      if (event.detail || event.detail === 0) {
        this.queryMaintenanceModeOptions();
      }
    }
  },
  clearForm(type) {
    let clearList = []
    let optionList = []

    if (type === 'faultTypeId') {
      clearList = ['maintenanceModeId']
      optionList = ['maintenanceModeOptions']
    }

    for (const item of clearList) {
      this.setData({
        [`formData.${item}`]: ''
      })
    }

    for (const item of optionList) {
      this.setData({
        [item]: []
      })
    }
  },
  async getFaultTypeOptions() {
    const params = {
      assetsTypeId: this.data.orderData.assetsTypeId,
      serviceMode: SERVICE_MODE.repair
    }
    openLoading()
    const [err, data] = await to(queryFaultTypeOptions(params))
    closeLoading()
    if (!err) {
      this.setData({
        faultTypeOption: data
      })
    }
  },

  async queryMaintenanceModeOptions() {
    const params = {
      faultTypeId: this.data.formData.faultTypeId
    }
    openLoading()
    const [err, data] = await to(queryMaintenanceModeOptions(params))
    closeLoading()

    if (!err) {
      this.setData({
        maintenanceModeOptions: data
      })
    }
  },

  onClickAttach() {
    const data = JSON.stringify(this.data.formData.addPartsOutParams);
    routeWithToken(`/page-repair/attachment-page/index?choosedData=${data}`)
  },

  setAttachmentData(data) {
    const addPartsOutParams = this.data.formData.addPartsOutParams

    if (!data) return;
    const index = addPartsOutParams.findIndex(item => item.partsId === data.partsId);

    if (index > -1) {
      addPartsOutParams[index].quantity = +addPartsOutParams[index].quantity + +data.quantity
    } else {
      addPartsOutParams.push({
        partsId: data.partsId,
        quantity: 1,
        storeId: data.storeId,
        companyId: this.data.orderData.companyId,
        comments: data.comments,
        partsName: data.partsName,
        storeName: data.storeName,
        quantityUnit: data.quantityUnit,
        partsModel: data.partsModel,
        inventoryQuantity: data.inventoryQuantity
      })
    }

    this.setData({
      ['formData.addPartsOutParams']: addPartsOutParams
    })
  },

  onAttachmentChange(event) {
    this.setData({
      ['formData.addPartsOutParams']: event.detail
    })
  },

  checkValidate() {
    const {
      faultTypeId,
      maintenanceModeId,
      difficultFault,
      innovativeSuggestions,
      operationContent
    } = this.data.formData;

    if (!operationContent) {
      showToast('请输入事件解决说明')
      return false;
    }

    if (!faultTypeId) {
      showToast('请选择故障事件')
      return false;
    }

    if (!maintenanceModeId) {
      showToast('请选择维护方式')
      return false;
    }

    if (difficultFault === DIFFICUIT_FAULT.yes) {
      if (!innovativeSuggestions) {
        showToast('请填写创新建议')
        return false
      }
    }

    return this.data.formData;
  },

  handleSubmit() {
    const result = this.checkValidate();

    if (!result) {
      return;
    }

    const params = {
      operationType: WORD_ORDER_OPERATION_TYPE.WORK_ORDER_FINISH,
      operationContent: result.operationContent,
      addPartsOutParams: JSON.stringify(result.addPartsOutParams),
      faultTypeId: result.faultTypeId,
      maintenanceModeId: result.maintenanceModeId,
      difficultFault: result.difficultFault,
      innovativeSuggestions: result.innovativeSuggestions,
      workOrderId: this.data.orderData.workOrderId,
      comments: result.comments
    }

    clearEmptyKey(params)
    this.submitData(params)
  },

  async submitData(params) {
    openLoading('提交中')
    const [err] = await to(updateWorkOrder(params))
    closeLoading()
    if (!err) {
      showToast({
        message: '提交成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad(1)
          }, 1000)
        }
      })
    }
  },
})